package com.leyou.order.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.IdWorker;
import com.leyou.item.client.ItemClient;
import com.leyou.item.pojo.Sku;
import com.leyou.order.dto.CartDTO;
import com.leyou.order.dto.OrderDTO;
import com.leyou.order.dto.OrderVO;
import com.leyou.order.mapper.OrderDetailMapper;
import com.leyou.order.mapper.OrderLogisticsMapper;
import com.leyou.order.mapper.OrderMapper;
import com.leyou.order.pojo.Order;
import com.leyou.order.pojo.OrderDetail;
import com.leyou.order.pojo.OrderLogistics;
import com.leyou.order.pojo.OrderStatusEnum;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.AddressDTO;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private UserClient userClient;

    @GlobalTransactional
    public Long buildOrder(OrderDTO orderDTO){
        //获取登录用户信息
        UserInfo userInfo = UserHolder.getUser();


        //1.保存订单表
        Order order = new Order();

        order.setOrderId(idWorker.nextId());//获取生产式ID
        order.setActualFee(1L);//实付金额
        order.setPromotionIds("");//优惠活动
        order.setPaymentType(1);//支付类型
        order.setPostFee(20L);//邮费
        order.setUserId(userInfo.getId());//下单用户
        order.setInvoiceType(0);//发票类型
        order.setSourceType(2);//订单来源
        order.setStatus(OrderStatusEnum.INIT.value());//订单状态

        //取出订单明细数据
        List<CartDTO> cartDTOS = orderDTO.getCarts();
        //取出skuId集合
        List<Long> skuIds = cartDTOS.stream().map(CartDTO::getSkuId).collect(Collectors.toList());
        //根据skuId集合查询Sku对象集合
        List<Sku> skuList = itemClient.findSkusByIds(skuIds);

        //把List<CartDTO>转换为Map<skuId,num>集合
        /**
         *toMap()方法：将List集合元素转移到Map集合汇总
         *   参数一： 将List集合的对象的哪个属性作为Map的key
         *   参数二： 将List集合的对象的哪个属性作为Map的value
         */
        Map<Long,Integer> cartMap = cartDTOS.stream().collect(Collectors.toMap(CartDTO::getSkuId,CartDTO::getNum));

        //mapToLong(): 取出集合元素进行运算，把运算结果转换为Long类型
        //sum(): 把每个mapToLong()方法的运算结果进行加总。
        Long totalFee = skuList.stream().mapToLong(sku->sku.getPrice()*cartMap.get(sku.getId())).sum();

        order.setTotalFee(totalFee);//计算总金额

        orderMapper.insert(order);

        //2.保存订单明细表
        if(skuList!=null){
            skuList.forEach(sku -> {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setId(idWorker.nextId());
                orderDetail.setOrderId(order.getOrderId());//订单编号
                orderDetail.setSkuId(sku.getId());
                orderDetail.setImage(sku.getImages());
                orderDetail.setTitle(sku.getTitle());
                orderDetail.setNum(cartMap.get(sku.getId()));
                orderDetail.setOwnSpec(sku.getOwnSpec());
                orderDetail.setPrice(sku.getPrice());

                orderDetailMapper.insert(orderDetail);
            });
        }

        //3.保存订单物流表
        //根据地址ID获取用户收货地址
        AddressDTO addressDTO = userClient.findAddressById(userInfo.getId(), orderDTO.getAddressId());

        //拷贝数据
        OrderLogistics orderLogistics = BeanHelper.copyProperties(addressDTO, OrderLogistics.class);
        //必须设置订单编号
        orderLogistics.setOrderId(order.getOrderId());//订单编号
        orderLogistics.setLogisticsNumber("SF000001");//物流单号
        orderLogistics.setLogisticsCompany("顺丰物流");//物流公司名称

        orderLogisticsMapper.insert(orderLogistics);

        //4.扣减库存量
        itemClient.minusStock(cartMap);

        //返回订单编号
        return order.getOrderId();
    }

    public OrderVO findOrderById(Long id) {
        //1.查询订单表数据
        Order order = orderMapper.selectById(id);
        //拷贝数据
        OrderVO orderVO = BeanHelper.copyProperties(order, OrderVO.class);

        //2.封装订单明细
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(id);
        QueryWrapper<OrderDetail> queryWrapper = Wrappers.query(orderDetail);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper);
        orderVO.setDetailList(orderDetails);

        //3.封装订单物流
        OrderLogistics orderLogistics = orderLogisticsMapper.selectById(id);
        orderVO.setLogistics(orderLogistics);
        return orderVO;
    }
}
